import 'dart:io';

import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/helper/app_update.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/r.dart';
import 'package:kxy_flutter_app/view/my/basic_info/change_password_view.dart';
import 'package:kxy_flutter_app/view/my/view_model/my_view_model.dart';
import 'package:kxy_flutter_app/view/root/view_model/auth_model.dart';
import 'package:kxy_flutter_app/view/root/view_model/navigation_model.dart';
import 'package:provider/provider.dart';

class SettingsView extends StatelessWidget {
  const SettingsView({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(title: Text('设置')),
      body: Column(
        verticalDirection: VerticalDirection.down,
        children: ListTile.divideTiles(
          tiles: [
            changePasswordTile(context),
            checkUpdateTile(context),
            logoutTile(context),
          ],
          context: context,
          color: Colors.black12,
        ).toList(),
      ),
    );
  }

  Widget logoutTile(BuildContext context) {
    return ListTile(
      leading: Image.asset(
        R.assetsImgMySignout,
        height: 24,
        width: 24,
      ),
      title: Text('退出登录'),
      onTap: () => logout(context),
    );
  }

  Widget changePasswordTile(BuildContext context) {
    return ListTile(
      leading: Image.asset(
        R.assetsImgMyPassword,
        height: 24,
        width: 24,
      ),
      title: Text('修改密码'),
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (cxt) => ChangePasswordView(),
          ),
        );
      },
    );
  }

  Widget checkUpdateTile(BuildContext context) {
    return ListTile(
      leading: Image.asset(
        R.assetsMyUpdate,
        height: 24,
        width: 24,
      ),
      title: Text('检查更新'),
      onTap: () async {
        var appUpdate = new AppUpdate();
        await appUpdate.checkUpdate(context);
      },
    );
  }

  Future logout(BuildContext context) async {
    var navModel = Provider.of<NavigationModel>(context, listen: false);
    var authModel = Provider.of<AuthModel>(context, listen: false);
    var myViewModel = Provider.of<MyViewModel>(context, listen: false);
    try {
      await Http.instance.post('/auth/logout', params: {
        'clientType': Platform.isIOS ? 2 : 1,
      });
      myViewModel.clear();
    } catch (e) {
      print(e);
    } finally {
      navModel.changeSelectIndex(0);
      authModel.unauthorize();
    }
    Navigator.pop(context);
  }
}
